<template>
  <div>
    <h2>录音功能</h2>
    <a-button @click="startRecording" :disabled="isRecording">开始录音</a-button>
    <a-button @click="stopRecording" :disabled="!isRecording">停止录音</a-button>
    <audio v-if="audioUrl" :src="audioUrl" controls></audio>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import axios from 'axios';

const isRecording = ref(false);
const audioUrl = ref(null);
let mediaRecorder = null;
let audioChunks = [];

const startRecording = async () => {
  audioChunks = [];
  const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
  mediaRecorder = new MediaRecorder(stream);

  mediaRecorder.ondataavailable = (event) => {
    audioChunks.push(event.data);
  };

  mediaRecorder.onstop = () => {
    const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
    console.log(audioBlob)
    // sendAudioToServer(audioBlob);
    audioUrl.value = URL.createObjectURL(audioBlob);
  };

  mediaRecorder.start();
  isRecording.value = true;
};

const stopRecording = () => {
  mediaRecorder.stop();
  isRecording.value = false;
};

const sendAudioToServer = (audioBlob) => {
  const formData = new FormData();
  formData.append('audio', audioBlob, 'recording.wav');

  axios.post('/your-backend-endpoint', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  })
      .then((response) => {
        console.log('录音上传成功:', response.data);
      })
      .catch((error) => {
        console.error('录音上传失败:', error);
      });
};
</script>

<style scoped>
button {
  margin: 5px;
}
</style>